package com.bsoft.gol.hcs.satisfaction.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.common.bean.request.FamilyMemberRequest;
import com.bsoft.gol.hcs.common.bean.response.AccountFamilyResponse;
import com.bsoft.gol.hcs.common.bean.response.HisBusCardResponse;
import com.bsoft.gol.hcs.common.entity.IdCard;
import com.bsoft.gol.hcs.common.entity.PatientMedicalCard;
import com.bsoft.gol.hcs.common.service.ICommonService;
import com.bsoft.gol.hcs.enumcase.*;
import com.bsoft.gol.hcs.followup.bean.request.FollowUpEducationDTO;
import com.bsoft.gol.hcs.followup.bean.request.FollowUpQuestionnaireDTO;
import com.bsoft.gol.hcs.his.bean.request.SendMsgRequest;
import com.bsoft.gol.hcs.his.bean.vo.MsgVariable;
import com.bsoft.gol.hcs.his.service.SendMsgService;
import com.bsoft.gol.hcs.satisfaction.bean.request.*;
import com.bsoft.gol.hcs.satisfaction.bean.response.EditorQuestionnaireDetailRes;
import com.bsoft.gol.hcs.satisfaction.bean.response.EditorQuestionnaireTitleRes;
import com.bsoft.gol.hcs.satisfaction.bean.response.QueryListByDoctorResponse;
import com.bsoft.gol.hcs.satisfaction.bean.vo.PatientSatisfactionSurveyVO;
import com.bsoft.gol.hcs.satisfaction.dao.PatientSatisfactionSurveyAnswerDAO;
import com.bsoft.gol.hcs.satisfaction.dao.PatientSatisfactionSurveyDAO;
import com.bsoft.gol.hcs.satisfaction.dao.SatisfactionProduceRecordDAO;
import com.bsoft.gol.hcs.satisfaction.entity.PatientSatisfactionSurvey;
import com.bsoft.gol.hcs.satisfaction.entity.PatientSatisfactionSurveyAnswer;
import com.bsoft.gol.hcs.satisfaction.entity.SatisfactionProduceRecord;
import com.bsoft.gol.hcs.satisfaction.service.ISatisfactionPlanService;
import com.bsoft.gol.hcs.service.rpc.IBaseParameterService;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.DuanLian;
import com.bsoft.gol.hcs.specialist.entity.FollowUpRoute;
import com.bsoft.gol.hcs.specialist.entity.SatisfactionHealthEducation;
import com.bsoft.gol.hcs.specialist.entity.SatisfactionRequisitionRecord;
import com.bsoft.gol.hcs.specialist.service.IFollowUpCommonService;
import com.bsoft.gol.hcs.specialist.service.impl.ProduceSatisfactionSurveyPlanServiceImpl;
import com.bsoft.gol.hcs.utils.*;
import com.bsoft.gol.hcs.visitrecord.dao.*;
import com.bsoft.gol.hcs.visitrecord.entity.VrApplicationFormRecord;
import com.bsoft.gol.hcs.visitrecord.entity.VrDispensingRecord;
import com.bsoft.gol.hcs.visitrecord.entity.VrInpatientVisitRecord;
import com.bsoft.gol.hcs.visitrecord.entity.VrSurgicalRecord;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.JSONUtils;
import ctd.util.KeyGenerator;
import hcn.base.VrOutpatientVisitRecord;
import hcn.bean.specialist.qo.GroupMemberRequest;
import hcn.specialist.DocTeamFusAuthority;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import service.rpc.IDocTeamRpcService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static com.bsoft.gol.hcs.enumcase.VisitRecordEnum.getEnumByKey;
import static com.bsoft.gol.hcs.utils.ShortUrlGenerator.getLongRandom;
import static com.bsoft.gol.hcs.utils.ShortUrlGenerator.numberConvertToDecimal;

/**
 * @author tongtp
 * @version v0.1
 * @className SatisfactionPlanServiceImpl
 * @description 满意度计划
 * @create 2020-09-01 16:50
 **/
@Slf4j
@SsdevService("satisfactionPlanService")
public class SatisfactionPlanServiceImpl implements ISatisfactionPlanService {

    private final static Logger logger = LoggerFactory.getLogger(SatisfactionPlanServiceImpl.class);
    private static ConcurrentHashMap<String, String> saveSurveyResultCache = new ConcurrentHashMap<>(512);
    @Autowired
    PatientSatisfactionSurveyDAO patientSatisfactionSurveyDAO;
    @Autowired
    IBaseParameterService baseParameterService;
    @Autowired
    PatientSatisfactionSurveyAnswerDAO patientSatisfactionSurveyAnswerDAO;
    @Autowired
    VrApplicationFormRecordDAO vrApplicationFormRecordDAO;
    @Autowired
    VrDispensingRecordDAO vrDispensingRecordDAO;
    @Autowired
    VrInpatientVisitRecordDAO vrInpatientVisitRecordDAO;
    @Autowired
    VrOutpatientVisitRecordDAO vrOutpatientVisitRecordDAO;
    @Autowired
    VrSurgicalRecordDAO vrSurgicalRecordDAO;
    @Autowired
    VrVisitDiagnosisDAO vrVisitDiagnosisDAO;
    @Autowired
    SatisfactionProduceRecordDAO satisfactionProduceRecordDAO;
    private BaseCache<String, String> sendMessageCache = new BaseCache<>(1024, 60);
    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private FollowUpRouteDAO followUpRouteDAO;
    @Autowired
    private ProduceSatisfactionSurveyPlanServiceImpl produceSatisfactionSurveyPlanService;
    @Value("${project_source}")
    private String projectSource;
    @Resource
    private DocTeamFusAuthorityDAO docTeamFusAuthorityDAO;
    @Autowired
    private SatisfactionHealthEducationDAO satisfactionHealthEducationDAO;
    @Autowired
    private SatisfactionRequisitionRecordDAO satisfactionRequisitionRecordDAO;
    @Autowired
    private IFollowUpCommonService followUpCommonService;
    @Autowired
    private IDocTeamRpcService docTeamRpcService;
    @Autowired
    private DuanLianDAO duanLianDAO;

    /**
     * @param request
     * @throws
     * @description: 查询满意度计划列表
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/2 11:50
     */
    @Override
    public QueryListByDoctorResponse queryListByDoctor(QueryListByDoctorRequest request) throws ControllerException {
        //查询医生加入的团队对应的路径
        GroupMemberRequest groupMemberRequest = new GroupMemberRequest();
        groupMemberRequest.setDocId(request.getDocId());
        groupMemberRequest.setTeamType("3");
        List<Long> teamIdList = docTeamRpcService.queryTeamIdList(groupMemberRequest);
        List<DocTeamFusAuthority> docTeamFusAuthorities = docTeamFusAuthorityDAO.queryByDocId(request.getDocId(), teamIdList);

        if (CollectionUtils.isEmpty(docTeamFusAuthorities)) {
            throw new ControllerException("该医生加入的团队没有任何满意度路径权限");
        } else {
            //得到要筛选的规则id集合
            List<Long> ruleIds = new ArrayList();
            if (CommonUtils.isNotNull(request.getSurveyRuleId())) {
                boolean matching = false;
                for (DocTeamFusAuthority docTeamFusAuthority :
                        docTeamFusAuthorities) {
                    if (request.getSurveyRuleId().equals(docTeamFusAuthority.getRouteId())) {
                        matching = true;
                    }
                }
                if (!matching) {
                    throw new ControllerException("该医生没有该满意度路径权限");
                } else {
                    ruleIds.add(request.getSurveyRuleId());
                }
            } else {
                for (DocTeamFusAuthority docTeamFusAuthority :
                        docTeamFusAuthorities) {
                    ruleIds.add(docTeamFusAuthority.getRouteId());
                }
            }
            QueryListByDoctorResponse queryListByDoctorResponse = new QueryListByDoctorResponse();
            Long count = patientSatisfactionSurveyDAO.queryCount(request, ruleIds);
            if (count > 0) {
                List<PatientSatisfactionSurvey> patientSatisfactionSurveys =
                        patientSatisfactionSurveyDAO.queryList(request, ruleIds);
                getQueryListByDoctorResponse(queryListByDoctorResponse, patientSatisfactionSurveys);
            }
            queryListByDoctorResponse.setTotal(count);
            return queryListByDoctorResponse;
        }
    }

    private void getQueryListByDoctorResponse(QueryListByDoctorResponse queryListByDoctorResponse,
                                              List<PatientSatisfactionSurvey> patientSatisfactionSurveys) {
        if (CommonUtils.isNotEmpty(patientSatisfactionSurveys)) {
            List<PatientSatisfactionSurveyVO> list = new ArrayList<>();
            queryListByDoctorResponse.setList(list);
            for (PatientSatisfactionSurvey patientSatisfactionSurvey :
                    patientSatisfactionSurveys) {
                PatientSatisfactionSurveyVO patientSatisfactionSurveyVO = new PatientSatisfactionSurveyVO();
                BeanUtils.copyProperties(patientSatisfactionSurvey, patientSatisfactionSurveyVO);
                list.add(patientSatisfactionSurveyVO);
                //查询健康宣教列表，查询问卷列表
                patientSatisfactionSurveyVO.setSatisfactionHealthEducationList(satisfactionHealthEducationDAO.queryByPatientSurveyId(patientSatisfactionSurveyVO.getPatientSurveyId()));
                patientSatisfactionSurveyVO.setSatisfactionRequisitionRecordList(satisfactionRequisitionRecordDAO.queryByPatientSurveyId(patientSatisfactionSurveyVO.getPatientSurveyId()));
            }
        }
    }


    /**
     * @param request
     * @throws
     * @description: 满意度调查记录
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/2 10:37
     */
    @Override
    public QueryListByDoctorResponse querySurveyList(QuerySurveyListRequest request) throws ControllerException {
        if (CommonUtils.isNull(request.getPageNo()) || CommonUtils.isNull(request.getPageSize())
                || (CommonUtils.isNull(request.getPatientId())
                && (CommonUtils.isNull(request.getCardType()) || CommonUtils.isNull(request.getCardNumber()))
                && (CommonUtils.isNull(request.getPatientMedicalCardType()) || CommonUtils.isNull(request.getPatientMedicalCardNumber())))) {
            throw new ControllerException("传入参数不能为空");
        }

        //问卷填写状态 0:未填写问卷   1:已填写问卷
        //为空则表示查询查询已填写问卷
        if (CommonUtils.isNull(request.getSurveyStatus())) {
            request.setSurveyStatus(SurveyStatusEnum.FILL_IN.getStatus());
        }
        QueryListByDoctorResponse queryListByDoctorResponse = new QueryListByDoctorResponse();
        List<String> patientIds = null;
        List<IdCard> idCards = null;
        List<PatientMedicalCard> patientMedicalCards = null;
        if (CommonUtils.isNotNull(request.getPatientId())) {
            patientIds = new ArrayList<>();
            patientIds.add(request.getPatientId());
        }
        if (CommonUtils.isNotNull(request.getCardType()) && CommonUtils.isNotNull(request.getCardNumber())) {
            idCards = new ArrayList<>();
            IdCard idCard = new IdCard();
            idCard.setCardNo(request.getCardNumber());
            idCard.setCardType(request.getCardType());
            idCards.add(idCard);
        }
        if (CommonUtils.isNotNull(request.getPatientMedicalCardType()) && CommonUtils.isNotNull(request.getPatientMedicalCardNumber())) {
            patientMedicalCards = new ArrayList<>();
            PatientMedicalCard patientMedicalCard = new PatientMedicalCard();
            patientMedicalCard.setPatientMedicalCardType(request.getPatientMedicalCardType());
            patientMedicalCard.setPatientMedicalCardNumber(request.getPatientMedicalCardNumber());
            patientMedicalCards.add(patientMedicalCard);
        }
        Long count = patientSatisfactionSurveyDAO.queryCount(patientIds, idCards, patientMedicalCards,
                request.getSurveyStatus());
        if (count > 0) {
            List<PatientSatisfactionSurvey> patientSatisfactionSurveys =
                    patientSatisfactionSurveyDAO.queryList(patientIds, idCards,
                            patientMedicalCards, request.getSurveyStatus(), request.getPageNo(), request.getPageSize());
            getQueryListByDoctorResponse(queryListByDoctorResponse, patientSatisfactionSurveys);
        }
        queryListByDoctorResponse.setTotal(count);
        return queryListByDoctorResponse;
    }

    /**
     * @param request
     * @throws
     * @description: 患者端查询满意度调查记录
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/2 10:37
     */
    @Override
    public QueryListByDoctorResponse querySurveyForPatient(QuerySurveyForPatientRequest request) throws ControllerException {
        FamilyMemberRequest memberRequest = new FamilyMemberRequest();
        memberRequest.setIncludeSelf(true);
        memberRequest.setUserId(request.getPatientUserId());
        BaseResponse<List<AccountFamilyResponse>> response = commonService.findFamilyMemberList(memberRequest);
        //TODO 改为RPC接口
        if (response == null || ResultCode.SUCCESS != response.getCode()) {
            throw new ControllerException("获取家庭成员列表失败");
        }
        List<AccountFamilyResponse> accountFamilys = response.getData();
        if (CollectionUtils.isEmpty(accountFamilys)) {
            throw new ControllerException("家庭成员列表为空");
        }
        QueryListByDoctorResponse queryListByDoctorResponse = new QueryListByDoctorResponse();
        List<String> patientIds = new ArrayList<>();
        List<IdCard> idCards = new ArrayList<>();
        List<PatientMedicalCard> patientMedicalCards = new ArrayList<>();
        for (AccountFamilyResponse accountFamilyResponse :
                accountFamilys) {
            if (CommonUtils.isNotNull(accountFamilyResponse.getCardType()) && CommonUtils.isNotNull(accountFamilyResponse.getCardNo())) {
                IdCard idCard = new IdCard();
                idCard.setCardNo(accountFamilyResponse.getCardNo());
                idCard.setCardType(accountFamilyResponse.getCardType());
                idCards.add(idCard);
            }
            if (!CollectionUtils.isEmpty(accountFamilyResponse.getHisBusCardList())) {
                for (HisBusCardResponse hisBusCardResponse :
                        accountFamilyResponse.getHisBusCardList()) {
                    if (CommonUtils.isNotNull(hisBusCardResponse.getPatientCode())) {
                        patientIds.add(hisBusCardResponse.getPatientCode());
                    }
                    if (CommonUtils.isNotNull(hisBusCardResponse.getPatientMedicalCardType())
                            && CommonUtils.isNotNull(hisBusCardResponse.getPatientMedicalCardNumber())) {
                        PatientMedicalCard patientMedicalCard = new PatientMedicalCard();
                        patientMedicalCard.setPatientMedicalCardType(hisBusCardResponse.getPatientMedicalCardType() +
                                "");
                        patientMedicalCard.setPatientMedicalCardNumber(hisBusCardResponse.getPatientMedicalCardNumber());
                        patientMedicalCards.add(patientMedicalCard);
                    }
                }
            }
        }
        Long count = patientSatisfactionSurveyDAO.queryCountForPatient(patientIds, idCards, patientMedicalCards,
                request.getSurveyStatus());
        if (count > 0) {
            List<PatientSatisfactionSurvey> patientSatisfactionSurveys =
                    patientSatisfactionSurveyDAO.queryListForPatient(patientIds, idCards,
                            patientMedicalCards, request.getSurveyStatus(), request.getPageNo(), request.getPageSize());
            getQueryListByDoctorResponse(queryListByDoctorResponse, patientSatisfactionSurveys);
        }
        queryListByDoctorResponse.setTotal(count);
        return queryListByDoctorResponse;
    }

    /**
     * @param request
     * @throws
     * @description: 生成计划
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/2 10:37
     */
    @Override
    public void produce(ProduceRequest request) throws ControllerException {
        if (!CommonUtils.isNull(request.getSurveyRuleId())) {
            FollowUpRoute followUpRoute = followUpRouteDAO.get(request.getSurveyRuleId());
            if (followUpRoute != null) {
                if (!FollowTypeEnum.FUS_SATISFACTION.getType().equals(followUpRoute.getFollowType())) {
                    throw new ControllerException("该路径不是满意度随访路径");
                }
                if (!EnableStatusEnum.ENABLE.getStatus().equals(followUpRoute.getStatus())) {
                    throw new ControllerException("该路径未启用");
                }
                produceSatisfactionSurveyPlanService.produce(followUpRoute, request.getOperatorId());
            } else {
                throw new ControllerException("路径不存在");
            }
        }
    }

    /**
     * @param request
     * @throws
     * @description: 保存满意度调查结果
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/2 11:50
     */
    @Override
    public void saveSurveyResult(SaveSurveyResultRequest request) throws ControllerException {
        String patientSurveyId = request.getPatientSurveyId().intern();
        synchronized (patientSurveyId) {
            if (saveSurveyResultCache.get(patientSurveyId) == null) {
                saveSurveyResultCache.put(patientSurveyId, patientSurveyId);
            } else {
                throw new ControllerException("请勿重复提交");
            }
        }
        try {
            PatientSatisfactionSurvey patientSatisfactionSurvey =
                    patientSatisfactionSurveyDAO.get(patientSurveyId);
            if (patientSatisfactionSurvey == null) {
                throw new ControllerException("满意度调查计划不存在");
            }
            if (SurveyWayEnum.getEnumByKey(request.getSurveyWay()) == null) {
                throw new ControllerException("调研方式字典不正确");
            }
            boolean update = false;

            //进行重复的userInfoId校验
//            PatientSatisfactionSurvey tempPatientSatisfactionSurvey =
//                    patientSatisfactionSurveyDAO.getByUserInfoId(request.getUserInfoId());
//            if (tempPatientSatisfactionSurvey != null
//                    && !tempPatientSatisfactionSurvey.getPatientSurveyId().equals(patientSurveyId)) {
//                throw new ControllerException("问卷填写答案唯一标识userInfoId与已有数据重复");
//            }
            Date now = new Date();
            patientSatisfactionSurvey.setSurveyId(request.getSurveyId());
            patientSatisfactionSurvey.setSurveyName(request.getSurveyName());
            patientSatisfactionSurvey.setSurveyTime(now);
            //如果是问卷随访，只有一份表单，随访状态可以置成功。 其它情况保持原有状态
            patientSatisfactionSurvey.setSurveyStatus("3".equals(String.valueOf(patientSatisfactionSurvey.getRouteDetailType()))==true?SurveyStatusEnum.FILL_IN.getStatus():patientSatisfactionSurvey.getSurveyStatus());
            patientSatisfactionSurvey.setGmtModified(now);
            patientSatisfactionSurvey.setModifyId(request.getSurveyId());
            patientSatisfactionSurvey.setSurveyWay(request.getSurveyWay());
            patientSatisfactionSurveyDAO.update(patientSatisfactionSurvey);


            //更新表单明细答案
            SatisfactionRequisitionRecord q = new SatisfactionRequisitionRecord();
            q.setRecordId(request.getPatientSurveyId());
            q.setQuestionnaireId(request.getQuestionnaireId());
            SatisfactionRequisitionRecord record = satisfactionRequisitionRecordDAO.selectOneWithLimit(q, "");
            if(Objects.nonNull(record)){
                //在有效期内未发起处理的问卷可以重新编辑答案提交
                if (SurveyStatusEnum.FILL_IN.getStatus().equals(record.getSurveyStatus())) {
                    update = true;
                }
                SatisfactionRequisitionRecord update1 = new SatisfactionRequisitionRecord();
                update1.setFormId(record.getFormId());
                update1.setUserInfoId(request.getUserInfoId());
                update1.setSurveyStatus(SurveyStatusEnum.FILL_IN.getStatus());
                update1.setSurveyId(request.getSurveyId());
                update1.setSurveyName(request.getSurveyName());
                update1.setSurveyTime(now);
                satisfactionRequisitionRecordDAO.updateSelective(update1);
            }

            logger.info(" 表单提交入参："+JSONObject.toJSONString(request));

            //更新就医记录表
            if (!update) {
                //拉取表单编辑器答案数据
                GetQuestionnaireDetailRequest detailRequest = new GetQuestionnaireDetailRequest();
                String questionnaireId = request.getQuestionnaireId();
                detailRequest.setQuestionnaireId(questionnaireId);
                detailRequest.setUserInfoId(request.getUserInfoId());
                //设备类型 1pc  2app
                detailRequest.setDeviceType("1");
                //展示类型 1表单题目预览展示  2表单题目答案展示
                detailRequest.setShowType("2");
                BaseResponse<EditorQuestionnaireDetailRes> questionnaireDetailResponse =
                        baseParameterService.getQuestionnaireDetail(detailRequest);
                logger.info("同步表单编辑器返回数据：{},满意度调查计划记录patientSurveyId：{}", questionnaireDetailResponse,
                        patientSurveyId);
                if (questionnaireDetailResponse.getCode() == ResultCode.SUCCESS) {
                    //保存问卷答案
                    //在有效期内未发起处理的问卷可以重新编辑答案提交的时候先删除原来的问卷答案,再重新保存
                    patientSatisfactionSurveyAnswerDAO.deleteSurveyAnswerByPatientSurveyIdAndQuestionnaireId(patientSurveyId,questionnaireId);
                    BigDecimal totalScore = saveQuestionnaireAnswer(request.getSurveyId(), patientSurveyId, questionnaireId,
                            questionnaireDetailResponse.getData());

                    patientSatisfactionSurvey.setSurveyScore(totalScore);
                    patientSatisfactionSurveyDAO.update(patientSatisfactionSurvey);
                } else {
                    throw new ControllerException("同步表单编辑器答案失败");
                }
            }
        } finally {
            saveSurveyResultCache.remove(patientSurveyId);
        }
    }


    /**
     * @param request
     * @throws
     * @description: 批量添加满意度调查计划
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/2 16:14
     */
    @Override
    public PatientSatisfactionSurvey addPlan(AddPlanRequest request) throws ControllerException {

        if (CommonUtils.isEmpty(request.getQuestionnaireList())
                || CommonUtils.isNull(request.getIsNotify()) || CommonUtils.isNull(request.getOperatorId())
                || CollectionUtils.isEmpty(request.getClinicalRecordIdList())) {
            throw new ControllerException("传入参数不能为空");
        }
        boolean isEmpty = false;
        for (ClinicalRecordRequest clinicalRecordRequest :
                request.getClinicalRecordIdList()) {
            if (CommonUtils.isNull(clinicalRecordRequest.getBusinessId()) || CommonUtils.isNull(clinicalRecordRequest.getBusinessType())) {
                isEmpty = true;
                break;
            }
        }
        if (isEmpty) {
            throw new ControllerException("传入参数不能为空");
        }

        //随访提前通知时间-天数
        Integer advanceNotifyDate = 0;
        if ("1".equals(request.getIsNotify()) && Objects.nonNull(request.getNotifyDate())) {
            advanceNotifyDate = followUpCommonService.getAdvanceNotifyDate(advanceNotifyDate, request.getNotifyDate());
        }

        List<PatientSatisfactionSurvey> list = new ArrayList<>();
        for (ClinicalRecordRequest clinicalRecordRequest : request.getClinicalRecordIdList()) {
            //保存满意度调查计划
           list.add(saveSatisfactionSurveyV2(request, clinicalRecordRequest.getBusinessId(), clinicalRecordRequest.getBusinessType(), advanceNotifyDate));
//            saveSatisfactionSurvey(now, clinicalRecordRequest.getBusinessId(), clinicalRecordRequest.getBusinessType()
//                    , request.getIsNotify(), request.getOperatorId(), request.getQuestionnaireList(), request.getEducationList(),
//                    request.getSurveyRuleId(), request.getSurveyRuleName(), false,
//                    null, null, null, null, null, null, null);
        }

        if (CommonUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    public static void main(String[] args) {

    }
    /**
     * @throws
     * @description: 发送满意度调查消息给所有人
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/3 16:23
     */
    @Override
    public BaseResponse sendSatisfactionSurveyMessageToAll() {
        List<PatientSatisfactionSurvey> patientSatisfactionSurveys = new ArrayList<>();
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        List<PatientSatisfactionSurvey> patientSatisfactionSurvey2 =
                patientSatisfactionSurveyDAO.queryUnsend(time,time);
        log.info("patientSatisfactionSurveys===>"+patientSatisfactionSurveys.size());
         for (PatientSatisfactionSurvey patientSatisfactionSurvey :patientSatisfactionSurvey2){
             patientSatisfactionSurveys.add(patientSatisfactionSurvey);
         }
         //发送住院的规则
        List<PatientSatisfactionSurvey> patientSatisfactionSurveys1 = patientSatisfactionSurveyDAO.queryUnsendForuserNew(time,time);
         log.info("patientSatisfactionSurveys1===>"+patientSatisfactionSurveys1.size());
        for (PatientSatisfactionSurvey patient:patientSatisfactionSurveys1) {
            patientSatisfactionSurveys.add(patient);
        }
        StringBuilder messageBuilder = new StringBuilder();

        log.info("------------list----"+patientSatisfactionSurveys.size());
//      log.info(patientSatisfactionSurveys.size()+patientSatisfactionSurveys.toString());
        if (!CollectionUtils.isEmpty(patientSatisfactionSurveys)) {
            BaseResponse baseResponse;
            for (PatientSatisfactionSurvey patientSatisfactionSurvey :
                    patientSatisfactionSurveys) {
                log.info("推送的人的数据========》patientSatisfactionSurvey"+patientSatisfactionSurveys.size());
                baseResponse = doSendSatisfactionSurveyMessage(patientSatisfactionSurvey);
                if (baseResponse.getCode() != ResultCode.SUCCESS) {
                    messageBuilder.append(baseResponse.getMessage());
                }
            }
        }
        return BaseRespUtil.setResultSuccess(messageBuilder.toString());
    }

//    public static void main(String[] args) {
//        Date date = new Date();
//        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        String time = format.format(date)+" 00:00:00";
//        System.out.println("time: "+time);
//    }
    @Override
    public BaseResponse sendSatisfactionSurveyMessageToAllNew( String startTime ,String endTime) {


        List<PatientSatisfactionSurvey> patientSatisfactionSurveys = new ArrayList<>();


        List<PatientSatisfactionSurvey> patientSatisfactionSurvey2 =
                patientSatisfactionSurveyDAO.queryUnsend(startTime,endTime);
        log.info("patientSatisfactionSurveys===>"+patientSatisfactionSurveys.size());
        for (PatientSatisfactionSurvey patientSatisfactionSurvey :patientSatisfactionSurvey2){
            patientSatisfactionSurveys.add(patientSatisfactionSurvey);
        }
        List<PatientSatisfactionSurvey> patientSatisfactionSurveys1 = patientSatisfactionSurveyDAO.queryUnsendForuserNew(startTime,endTime);
        log.info("patientSatisfactionSurveys1===>"+patientSatisfactionSurveys1.size());
        for (PatientSatisfactionSurvey patient:patientSatisfactionSurveys1) {
            patientSatisfactionSurveys.add(patient);
        }
        StringBuilder messageBuilder = new StringBuilder();

        log.info("------------list----"+patientSatisfactionSurveys.size());
        log.info(patientSatisfactionSurveys.size()+patientSatisfactionSurveys.toString());
        if (!CollectionUtils.isEmpty(patientSatisfactionSurveys)) {
            BaseResponse baseResponse;
            for (PatientSatisfactionSurvey patientSatisfactionSurvey :
                    patientSatisfactionSurveys) {
                baseResponse = doSendSatisfactionSurveyMessage(patientSatisfactionSurvey);
                if (baseResponse.getCode() != ResultCode.SUCCESS) {
                    messageBuilder.append(baseResponse.getMessage());
                }
            }
        }
        return BaseRespUtil.setResultSuccess(messageBuilder.toString());
    }

    /**
     * @param request
     * @throws
     * @description: 发送满意度调查消息
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/9/4 9:40
     */
    @Override
    public void sendSatisfactionSurveyMessage(SatisfactionSurveyMessageRequest request) throws ControllerException {
        PatientSatisfactionSurvey patientSatisfactionSurvey =
                patientSatisfactionSurveyDAO.get(request.getPatientSurveyId());
        if (patientSatisfactionSurvey == null) {
            throw new ControllerException("满意度调查计划不存在");
        }
        if (SurveyStatusEnum.FILL_IN.getStatus().equals(patientSatisfactionSurvey.getSurveyStatus())) {
            throw new ControllerException("该满意度调查问卷已填写，不允许推送满意度调查消息");
        }
        BaseResponse response = doSendSatisfactionSurveyMessage(patientSatisfactionSurvey);
        if (response.getCode() != ResultCode.SUCCESS) {
            throw new ControllerException(response.getMessage());
        }
    }


    /**
     * @param patientSatisfactionSurvey
     * @throws
     * @description: 发送满意度调查消息
     * @return: void
     * @author: tongtp
     * @date: 2020/9/3 16:56
     */
    private BaseResponse doSendSatisfactionSurveyMessage(PatientSatisfactionSurvey patientSatisfactionSurvey) {
        String patientSurveyId = patientSatisfactionSurvey.getPatientSurveyId();
        log.info("patientSurveyId--->"+patientSurveyId);
//        if (sendMessageCache.get(patientSurveyId) == null) {
//            sendMessageCache.put(patientSurveyId, patientSurveyId);
//        } else {
//            return BaseRespUtil.setResultError("1分钟内不允许重复发送");
//        }
        BaseResponse baseResponse = new BaseResponse();
        //默认成功
        if (CommonUtils.isNull(patientSatisfactionSurvey.getTelephone())){
            patientSatisfactionSurvey.setTelephone("17703775451");
        } else {
            if (!Utils.isPhone(patientSatisfactionSurvey.getTelephone())){
                return BaseRespUtil.setResultError("不是手机号码或者非法手机号码,不能发送");
            }
        }

        baseResponse.setCode(ResultCode.SUCCESS);
        List<MsgVariable> msgVariableList = new ArrayList<>();
        SendMsgRequest sendMsgRequest = new SendMsgRequest();
        if (InterfaceTypeEnum.HOL.getCode().equals(projectSource)) {
            ////0 后台管理 1 居民 2 医生
            sendMsgRequest.setUserType(1);
            sendMsgRequest.setBusinessType(138);
            MsgVariable msgVariable = new MsgVariable();
            msgVariable.setMsgVariableKey("#患者姓名#");
            msgVariable.setMsgVariableValue(patientSatisfactionSurvey.getPatientName());
            msgVariableList.add(msgVariable);
            MsgVariable msgVariable1 = new MsgVariable();
            msgVariable1.setMsgVariableKey("patientSurveyId");
            msgVariable1.setMsgVariableValue(patientSurveyId);
            msgVariableList.add(msgVariable1);
            sendMsgRequest.setMsgVariableList(msgVariableList);
            sendMsgRequest.setPatientCode(patientSatisfactionSurvey.getPatientId());
            sendMsgRequest.setMobile(patientSatisfactionSurvey.getTelephone());
            sendMsgRequest.setPatientIdentityCardNumber(patientSatisfactionSurvey.getCardNumber());
            sendMsgRequest.setPatientIdentityCardType(patientSatisfactionSurvey.getCardType());
            sendMsgRequest.setPatientMedicalCardType(patientSatisfactionSurvey.getPatientMedicalCardType());
            sendMsgRequest.setPatientMedicalCardNumber(patientSatisfactionSurvey.getPatientMedicalCardNumber());
            baseResponse = sendMsgService.productionMessage(sendMsgRequest);
            //TODO 改为RPC接口
        } else if (InterfaceTypeEnum.GOL.getCode().equals(projectSource)) {
            if (StringUtils.hasText(patientSatisfactionSurvey.getTelephone())&&(patientSatisfactionSurvey.getTelephone().length()==11)) {
//                JSONObject jsonParams = new JSONObject();
//                jsonParams.put("phoneNo", patientSatisfactionSurvey.getTelephone());
//                jsonParams.put("name", patientSatisfactionSurvey.getPatientName());
//                //todo lin rpc 改造
//                String url = Constants.GOL_FAMILY_URL + Constants.SEND_SATISFACTION_SURVEY_MESSAGE;
//                return sendMsgService.getJsonObject(url, jsonParams);
//                //TODO 改为RPC接口

                String questionnaireId ="";
                //添加的问卷
                List<SatisfactionRequisitionRecord> list =satisfactionRequisitionRecordDAO.queryByPatientSurveyId(patientSatisfactionSurvey.getPatientSurveyId());
                if(list.size()>0){
                    questionnaireId =list.get(0).getQuestionnaireId();
                }

//                VrOutpatientVisitRecord vrOutpatientVisitRecord = vrOutpatientVisitRecordDAO.get(patientSatisfactionSurvey.getBusinessId());
//                String startTime =  DateUtil.dateFormate(vrOutpatientVisitRecord.getStartTime(),"yyyy-MM-dd");

                StringBuffer urlMessage = new StringBuffer();
                urlMessage.append("https://wx.hz3yy.com/gol-specialist-web-dist/#/iframeEditor?");
                urlMessage.append("id=").append(questionnaireId).append("&").append("userId=").append(SM4Utils.encryptData_CBC(patientSatisfactionSurvey.getCardNumber())).append("&patientSurveyId=")
                        .append(patientSatisfactionSurvey.getPatientSurveyId()).append("&type=preview");

                DuanLian durlMapping = new DuanLian();
                long id = getLongRandom();
                String durl = numberConvertToDecimal(id, 62);
                durlMapping.setId(id);
                durlMapping.setDurl(durl);
                durlMapping.setUrl(urlMessage.toString());
                durlMapping.setCreateTime(new Date());
                durlMapping.setPhone(patientSatisfactionSurvey.getTelephone());
                duanLianDAO.save(durlMapping);
                //短信推送
                //String content= patientSatisfactionSurvey.getPatientName()+"您好,您于"+startTime+"在我院"+patientSatisfactionSurvey.getDepartmentName()+"就诊,接诊医生"+patientSatisfactionSurvey.getDoctorName()+"。恳请您对"+patientSatisfactionSurvey.getDoctorName()+"医生的诊疗服务进行评价。谢谢！评价链接：https://weixin.hz3yy.com/hcn-specialist/a/"+durl+"  回复TD拒收";
                JSONObject jsonParams = new  JSONObject();
                jsonParams.put("type",patientSatisfactionSurvey.getBusinessType());
                jsonParams.put("telephone",patientSatisfactionSurvey.getTelephone());
                jsonParams.put("cardNumber",patientSatisfactionSurvey.getCardNumber());
                jsonParams.put("patientName",patientSatisfactionSurvey.getPatientName());
                jsonParams.put("content","https://wx.hz3yy.com/hcn-specialist/a/"+durl);
                jsonParams.put("doctorName",patientSatisfactionSurvey.getDepartmentName());
                logger.info("入参"+jsonParams);
                List<DuanLian> forCreateTime = duanLianDAO.getForCreateTime(new Date(new Date().getTime() - 168 * 60 * 60 * 1000), new Date(), patientSatisfactionSurvey.getTelephone());
                log.info("查询记录=====》"+ JSONUtils.writeValueAsString(forCreateTime));
                String doPost = HttpClientUtils.doPost("http://10.10.10.16:80/wechatclient-ssyy/api/sendMessageForUser", jsonParams.toString());
                JSONObject json = JSONObject.parseObject(doPost);
                baseResponse.setCode(json.getInteger("code"));
                baseResponse.setMessage(json.getString("message"));
                baseResponse.setData(json.getString("data"));
                logger.info("返回结果"+doPost);


            } else {
                //健康通的没有手机号不进行短信推送
                baseResponse.setCode(ResultCode.PARAMETERS_EMPTY);
                baseResponse.setMessage("手机号不正确，无法进行短信发送");
            }
        }
        //实际通知状态：0 未通知 1 已通知  2 通知失败
        Date now = new Date();
        if (ResultCode.SUCCESS == baseResponse.getCode() && "0".equals(patientSatisfactionSurvey.getNotifyStatus())) {
            patientSatisfactionSurvey.setNotifyStatus("1");
            patientSatisfactionSurvey.setNotifyTime(now);
            patientSatisfactionSurvey.setRelation(baseResponse.getData().toString());
            patientSatisfactionSurveyDAO.update(patientSatisfactionSurvey);
        }
        if (ResultCode.SUCCESS != baseResponse.getCode()) {
            patientSatisfactionSurvey.setNotifyStatus("2");
            patientSatisfactionSurveyDAO.update(patientSatisfactionSurvey);
        }
        return baseResponse;
    }

    /**
     * @param businessType
     * @param businessId
     * @throws
     * @description: 更新调查次数
     * @return: void
     * @author: tongtp
     * @date: 2020/9/4 16:06
     */
    private void updateSurveyNumber(String businessType, String businessId) {
        VisitRecordEnum enumByKey = getEnumByKey(businessType);
        if (enumByKey != null) {
            switch (enumByKey) {
                case OUTPATIENT_VISIT_RECORD:
                    VrOutpatientVisitRecord vrOutpatientVisitRecord =
                            vrOutpatientVisitRecordDAO.get(businessId);
                    if (vrOutpatientVisitRecord != null) {
                        vrOutpatientVisitRecord.setSurveyNumber(vrOutpatientVisitRecord.getSurveyNumber() + 1);
                        vrOutpatientVisitRecordDAO.update(vrOutpatientVisitRecord);
                    }
                    break;
                case INPATIENT_VISIT_RECORD:
                    VrInpatientVisitRecord vrInpatientVisitRecord =
                            vrInpatientVisitRecordDAO.get(businessId);
                    if (vrInpatientVisitRecord != null) {
                        vrInpatientVisitRecord.setSurveyNumber(vrInpatientVisitRecord.getSurveyNumber() + 1);
                        vrInpatientVisitRecordDAO.update(vrInpatientVisitRecord);
                    }
                    break;
                case SURGICAL_RECORD:
                    VrSurgicalRecord vrSurgicalRecord =
                            vrSurgicalRecordDAO.get(businessId);
                    if (vrSurgicalRecord != null) {
                        vrSurgicalRecord.setSurveyNumber(vrSurgicalRecord.getSurveyNumber() + 1);
                        vrSurgicalRecordDAO.update(vrSurgicalRecord);
                    }
                    break;
                case INSPECTION_RECORD:
                case CHECK_RECORD:
                case TREATMENT_RECORD:
                    VrApplicationFormRecord vrApplicationFormRecord =
                            vrApplicationFormRecordDAO.get(businessId);
                    if (vrApplicationFormRecord != null) {
                        vrApplicationFormRecord.setSurveyNumber(vrApplicationFormRecord.getSurveyNumber() + 1);
                        vrApplicationFormRecordDAO.update(vrApplicationFormRecord);
                    }
                    break;
                case DISPENSING_RECORD:
                    VrDispensingRecord vrDispensingRecord =
                            vrDispensingRecordDAO.get(businessId);
                    if (vrDispensingRecord != null) {
                        vrDispensingRecord.setSurveyNumber(vrDispensingRecord.getSurveyNumber() + 1);
                        vrDispensingRecordDAO.update(vrDispensingRecord);
                    }
                    break;
                default:
                    break;
            }
        }
    }


    /**
     * 保存问卷答案
     * @param doctorId  操作的医生工号
     * @param patientSurveyId  满意度随访主键
     * @param questionnaireId  表单id
     * @param data  编辑器表单详情
     */
    private BigDecimal saveQuestionnaireAnswer(String doctorId, String patientSurveyId,
                                         String questionnaireId,
                                         EditorQuestionnaireDetailRes data) {
        BigDecimal totalScore = BigDecimal.ZERO;
        Date now = new Date();
        SatisfactionRequisitionRecord query = new SatisfactionRequisitionRecord();
        query.setRecordId(patientSurveyId);
        query.setQuestionnaireId(questionnaireId);
        SatisfactionRequisitionRecord record = satisfactionRequisitionRecordDAO.selectOneWithLimit(query, "");
        if(Objects.isNull(record)){
            return totalScore;
        }


        List<EditorQuestionnaireTitleRes> titles = data.getTitles();
        if (!CollectionUtils.isEmpty(titles)) {
            PatientSatisfactionSurveyAnswer patientSatisfactionSurveyAnswer =
                    new PatientSatisfactionSurveyAnswer();
            patientSatisfactionSurveyAnswer.setPatientSurveyId(patientSurveyId);
            //没有患者就诊调查名称，暂时用问卷名称代替
            patientSatisfactionSurveyAnswer.setPatientSurveyName(record.getQuestionnaireName());
            patientSatisfactionSurveyAnswer.setQuestionnaireId(questionnaireId);
            patientSatisfactionSurveyAnswer.setQuestionnaireName(record.getQuestionnaireName());
            patientSatisfactionSurveyAnswer.setCreatorId(doctorId);
            patientSatisfactionSurveyAnswer.setGmtCreate(now);
            patientSatisfactionSurveyAnswer.setModifyId(doctorId);
            patientSatisfactionSurveyAnswer.setGmtModified(now);

            for (EditorQuestionnaireTitleRes editorQuestionnaireTitleRes :
                    titles) {
                patientSatisfactionSurveyAnswer.setTitleId(editorQuestionnaireTitleRes.getTitleId());
                //把题目题型名称拼接在题目名称前面
                patientSatisfactionSurveyAnswer.setTitleName("【" + TitleType.getEnumByKey(editorQuestionnaireTitleRes.getWidgetType()).getName() + "】" + editorQuestionnaireTitleRes.getTitleName());
                if (editorQuestionnaireTitleRes.getEditorAnswer() != null) {
                    patientSatisfactionSurveyAnswer.setSurveyAnswerId(Utils.getUUID());
                    patientSatisfactionSurveyAnswer.setAnswerId(editorQuestionnaireTitleRes.getEditorAnswer().getAnswerId());
                    if (Byte.valueOf("4").equals(editorQuestionnaireTitleRes.getWidgetType())) {
                        //字典选择类取其他字段
                        patientSatisfactionSurveyAnswer.setAnswerName(editorQuestionnaireTitleRes.getEditorAnswer().getAnswerDesc());
                    } else {
                        patientSatisfactionSurveyAnswer.setAnswerName(editorQuestionnaireTitleRes.getEditorAnswer().getAnswerContent());
                    }
                    //处理状态0：以表中的注释为0无需处理1未处理2已处理
                    patientSatisfactionSurveyAnswer.setProcessingStatus("1");
                    //是否通知患者，0不通知，1通知
                    patientSatisfactionSurveyAnswer.setNotifyFlag("0");
                    //存储医生id
                    patientSatisfactionSurveyAnswer.setProcessingDoctorId(doctorId);
                    patientSatisfactionSurveyAnswer.setOptionId(editorQuestionnaireTitleRes.getEditorAnswer().getOptionId());
                    patientSatisfactionSurveyAnswer.setGrade(editorQuestionnaireTitleRes.getEditorAnswer().getGrade());
                    if(null != editorQuestionnaireTitleRes.getEditorAnswer().getGrade()){
                        totalScore = totalScore.add(editorQuestionnaireTitleRes.getEditorAnswer().getGrade());
                    }

                    String answerAbnormal= editorQuestionnaireTitleRes.getEditorAnswer().getAnsweAbnormal() == null ? null : editorQuestionnaireTitleRes.getEditorAnswer().getAnsweAbnormal().toString();
                    patientSatisfactionSurveyAnswer.setAnswerAbnormal(answerAbnormal);
                    patientSatisfactionSurveyAnswerDAO.save(patientSatisfactionSurveyAnswer);
                }
            }
        }
        BigDecimal grade = data.getTitles().get(0).getEditorAnswer().getGrade();
        log.info("分数=======》"+ grade.divide(BigDecimal.valueOf(10)));
        if (CommonUtils.isNotEmpty(data.getTitles().get(0).getEditorAnswer().getGrade())){
            return  (data.getTitles().get(0).getEditorAnswer().getGrade().divide(BigDecimal.valueOf(10)));
        } else {
            return  new BigDecimal("0");
        }
        //return totalScore;
    }

    /**
     * 保存满意度调查计划 (取药/发药)
     *
     * @author tongtp
     * @date: 2020/9/7 16:14
     */
    @Deprecated
    private void savePatientSatisfactionSurvey(PatientSatisfactionSurvey patientSatisfactionSurvey,
                                               VrDispensingRecord record) {
        patientSatisfactionSurvey.setOrganizationId(record.getOrganizationId());
        patientSatisfactionSurvey.setOrganizationName(record.getOrganizationName());
        patientSatisfactionSurvey.setDepartmentId(record.getDepartmentId());
        patientSatisfactionSurvey.setDepartmentName(record.getDepartmentName());
        patientSatisfactionSurvey.setDoctorId(record.getDoctorId());
        patientSatisfactionSurvey.setDoctorName(record.getDoctorName());
        patientSatisfactionSurvey.setPatientId(record.getPatientId());
        patientSatisfactionSurvey.setCardType(record.getCardType());
        patientSatisfactionSurvey.setCardNumber(record.getCardNumber());
        patientSatisfactionSurvey.setPatientMedicalCardType(record.getPatientMedicalCardType());
        patientSatisfactionSurvey.setPatientMedicalCardNumber(record.getPatientMedicalCardNumber());
        patientSatisfactionSurvey.setPatientName(record.getPatientName());
        patientSatisfactionSurvey.setPatientBirthday(record.getPatientBirthday());
        patientSatisfactionSurvey.setPatientSex(record.getPatientSex());
        patientSatisfactionSurvey.setPatientAge(record.getPatientAge());
        patientSatisfactionSurvey.setTelephone(record.getTelephone());
        patientSatisfactionSurvey.setAddress(record.getAddress());
        patientSatisfactionSurvey.setCompanionName(record.getCompanionName());
        patientSatisfactionSurvey.setCompanionPhone(record.getCompanionPhone());
        patientSatisfactionSurvey.setRelation(record.getCompanionRelationship());
        patientSatisfactionSurveyDAO.save(patientSatisfactionSurvey);
    }

    /**
     * @param patientSatisfactionSurvey
     * @param record
     * @throws
     * @description: 保存满意度调查计划 (治疗记录,处置记录)
     * @return: void
     * @author: tongtp
     * @date: 2020/9/7 16:14
     */
    @Deprecated
    private void savePatientSatisfactionSurvey(PatientSatisfactionSurvey patientSatisfactionSurvey,
                                               VrApplicationFormRecord record) {
        patientSatisfactionSurvey.setOrganizationId(record.getOrganizationId());
        patientSatisfactionSurvey.setOrganizationName(record.getOrganizationName());
        patientSatisfactionSurvey.setDepartmentId(record.getOpenDepartmentId());
        patientSatisfactionSurvey.setDepartmentName(record.getOpenDepartmentName());
        patientSatisfactionSurvey.setDoctorId(record.getOpenDoctorId());
        patientSatisfactionSurvey.setDoctorName(record.getOpenDoctorName());
        patientSatisfactionSurvey.setPatientId(record.getPatientId());
        patientSatisfactionSurvey.setCardType(record.getCardType());
        patientSatisfactionSurvey.setCardNumber(record.getCardNumber());
        patientSatisfactionSurvey.setPatientMedicalCardType(record.getPatientMedicalCardType());
        patientSatisfactionSurvey.setPatientMedicalCardNumber(record.getPatientMedicalCardNumber());
        patientSatisfactionSurvey.setPatientName(record.getPatientName());
        patientSatisfactionSurvey.setPatientBirthday(record.getPatientBirthday());
        patientSatisfactionSurvey.setPatientSex(record.getPatientSex());
        patientSatisfactionSurvey.setPatientAge(record.getPatientAge());
        patientSatisfactionSurvey.setTelephone(record.getTelephone());
        patientSatisfactionSurvey.setAddress(record.getAddress());
        patientSatisfactionSurvey.setCompanionName(record.getCompanionName());
        patientSatisfactionSurvey.setCompanionPhone(record.getCompanionPhone());
        patientSatisfactionSurvey.setRelation(record.getCompanionRelationship());
        patientSatisfactionSurveyDAO.save(patientSatisfactionSurvey);
    }

    /**
     * @param patientSatisfactionSurvey
     * @param record
     * @throws
     * @description: 保存满意度调查计划 (手术记录)
     * @return: void
     * @author: tongtp
     * @date: 2020/9/7 16:14
     */
    @Deprecated
    private void savePatientSatisfactionSurvey(PatientSatisfactionSurvey patientSatisfactionSurvey,
                                               VrSurgicalRecord record) {
        patientSatisfactionSurvey.setOrganizationId(record.getOrganizationId());
        patientSatisfactionSurvey.setOrganizationName(record.getOrganizationName());
        patientSatisfactionSurvey.setDepartmentId(record.getDepartmentId());
        patientSatisfactionSurvey.setDepartmentName(record.getDepartmentName());
        patientSatisfactionSurvey.setDoctorId(record.getSurgeonDoctorId());
        patientSatisfactionSurvey.setDoctorName(record.getSurgeonDoctorName());
        patientSatisfactionSurvey.setPatientId(record.getPatientId());
        patientSatisfactionSurvey.setCardType(record.getCardType());
        patientSatisfactionSurvey.setCardNumber(record.getCardNumber());
        patientSatisfactionSurvey.setPatientMedicalCardType(record.getPatientMedicalCardType());
        patientSatisfactionSurvey.setPatientMedicalCardNumber(record.getPatientMedicalCardNumber());
        patientSatisfactionSurvey.setPatientName(record.getPatientName());
        patientSatisfactionSurvey.setPatientBirthday(record.getPatientBirthday());
        patientSatisfactionSurvey.setPatientSex(record.getPatientSex());
        patientSatisfactionSurvey.setPatientAge(record.getPatientAge());
        patientSatisfactionSurvey.setTelephone(record.getTelephone());
        patientSatisfactionSurvey.setAddress(record.getAddress());
        patientSatisfactionSurvey.setCompanionName(record.getCompanionName());
        patientSatisfactionSurvey.setCompanionPhone(record.getCompanionPhone());
        patientSatisfactionSurvey.setRelation(record.getCompanionRelationship());
        patientSatisfactionSurveyDAO.save(patientSatisfactionSurvey);
    }

    /**
     * @param patientSatisfactionSurvey
     * @param record
     * @throws
     * @description: 保存满意度调查计划 (住院)
     * @return: void
     * @author: tongtp
     * @date: 2020/9/7 16:14
     */
    @Deprecated
    private void savePatientSatisfactionSurvey(PatientSatisfactionSurvey patientSatisfactionSurvey,
                                               VrInpatientVisitRecord record) {
        patientSatisfactionSurvey.setOrganizationId(record.getOrganizationId());
        patientSatisfactionSurvey.setOrganizationName(record.getOrganizationName());
        patientSatisfactionSurvey.setDepartmentId(record.getDepartmentId());
        patientSatisfactionSurvey.setDepartmentName(record.getDepartmentName());
        patientSatisfactionSurvey.setDoctorId(record.getAttendingDoctorId());
        patientSatisfactionSurvey.setDoctorName(record.getAttendingDoctorName());
        patientSatisfactionSurvey.setPatientId(record.getPatientId());
        patientSatisfactionSurvey.setCardType(record.getCardType());
        patientSatisfactionSurvey.setCardNumber(record.getCardNumber());
        patientSatisfactionSurvey.setPatientMedicalCardType(record.getPatientMedicalCardType());
        patientSatisfactionSurvey.setPatientMedicalCardNumber(record.getPatientMedicalCardNumber());
        patientSatisfactionSurvey.setPatientName(record.getPatientName());
        patientSatisfactionSurvey.setPatientBirthday(record.getPatientBirthday());
        patientSatisfactionSurvey.setPatientSex(record.getPatientSex());
        patientSatisfactionSurvey.setPatientAge(record.getPatientAge());
        patientSatisfactionSurvey.setTelephone(record.getTelephone());
        patientSatisfactionSurvey.setAddress(record.getAddress());
        patientSatisfactionSurvey.setCompanionName(record.getCompanionName());
        patientSatisfactionSurvey.setCompanionPhone(record.getCompanionPhone());
        patientSatisfactionSurvey.setRelation(record.getCompanionRelationship());
        patientSatisfactionSurvey.setHospitalNumber(record.getInHospitalRecordNumber());
        patientSatisfactionSurveyDAO.save(patientSatisfactionSurvey);
    }

    /**
     * @param patientSatisfactionSurvey
     * @param record
     * @throws
     * @description: 保存满意度调查计划  (门诊)
     * @return: void
     * @author: tongtp
     * @date: 2020/9/7 16:14
     */
    @Deprecated
    private void savePatientSatisfactionSurvey(PatientSatisfactionSurvey patientSatisfactionSurvey,
                                               VrOutpatientVisitRecord record) {
        patientSatisfactionSurvey.setOrganizationId(record.getOrganizationId());
        patientSatisfactionSurvey.setOrganizationName(record.getOrganizationName());
        patientSatisfactionSurvey.setDepartmentId(record.getDepartmentId());
        patientSatisfactionSurvey.setDepartmentName(record.getDepartmentName());
        patientSatisfactionSurvey.setDoctorId(record.getDoctorId());
        patientSatisfactionSurvey.setDoctorName(record.getDoctorName());
        patientSatisfactionSurvey.setPatientId(record.getPatientId());
        patientSatisfactionSurvey.setCardType(record.getCardType());
        patientSatisfactionSurvey.setCardNumber(record.getCardNumber());
        patientSatisfactionSurvey.setPatientMedicalCardType(record.getPatientMedicalCardType());
        patientSatisfactionSurvey.setPatientMedicalCardNumber(record.getPatientMedicalCardNumber());
        patientSatisfactionSurvey.setPatientName(record.getPatientName());
        patientSatisfactionSurvey.setPatientBirthday(record.getPatientBirthday());
        patientSatisfactionSurvey.setPatientSex(record.getPatientSex());
        patientSatisfactionSurvey.setPatientAge(record.getPatientAge());
        patientSatisfactionSurvey.setTelephone(record.getTelephone());
        patientSatisfactionSurvey.setAddress(record.getAddress());
        patientSatisfactionSurvey.setCompanionName(record.getCompanionName());
        patientSatisfactionSurvey.setCompanionPhone(record.getCompanionPhone());
        patientSatisfactionSurvey.setRelation(record.getCompanionRelationship());
        patientSatisfactionSurveyDAO.save(patientSatisfactionSurvey);
    }

    /**
     * 保存满意度计划v2
     */
    private PatientSatisfactionSurvey saveSatisfactionSurveyV2(AddPlanRequest request, String businessId, String businessType, Integer advanceNotifyDate) {
        String isNotify = request.getIsNotify();
        String operatorId = request.getOperatorId();
        Date now = new Date();
        Date planTime = Objects.isNull(request.getPlanTime()) ? now : request.getPlanTime();
        Date planNotifyTime = DateUtils.addDays(planTime, advanceNotifyDate);
        PatientSatisfactionSurvey survey = new PatientSatisfactionSurvey();
        if (isNotify == null) {
            //是否通知患者，0不通知，1通知
            isNotify = "0";
        }
        String routeDetailType = request.getRouteDetailType();
        routeDetailType = StringUtils.isEmpty(routeDetailType) ? RouteDetailTypeEnum.YHSF.getType() : routeDetailType;
        survey.setRouteDetailType(Byte.parseByte(routeDetailType));
        survey.setIsNotify(isNotify);
        survey.setProcessingStatus("0");
        survey.setCreatorId(operatorId);
        survey.setGmtCreate(now);
        survey.setModifyId(operatorId);
        survey.setGmtModified(now);
        survey.setSurveyStatus("0");
        survey.setNotifyStatus("0");
        survey.setSurveySource("2");
        //临时随访的路径为0 代表手动添加的路径
        survey.setSurveyRuleId(0L);
        survey.setSurveyRuleName("手动设置的随访路径");
        //居民对处理结果的确认状态 1：已确认   0：未确认
        survey.setConfirmStatus("0");
        survey.setBusinessId(businessId);
        survey.setBusinessType(businessType);

        survey.setPatientSurveyId(Utils.getUUID());
        survey.setPlanSurveyTime(planNotifyTime);
        survey.setPlanTime(planTime);
        VisitRecordEnum enumByKey = getEnumByKey(businessType);
        if (enumByKey != null) {
            switch (enumByKey) {
                case OUTPATIENT_VISIT_RECORD:
                    VrOutpatientVisitRecord vrOutpatientVisitRecord =
                            vrOutpatientVisitRecordDAO.get(businessId);
                    if (vrOutpatientVisitRecord != null) {
                        savePatientSatisfactionSurvey(survey, vrOutpatientVisitRecord);
                    }
                    break;
                case INPATIENT_VISIT_RECORD:
                    VrInpatientVisitRecord vrInpatientVisitRecord =
                            vrInpatientVisitRecordDAO.get(businessId);
                    if (vrInpatientVisitRecord != null) {
                        savePatientSatisfactionSurvey(survey, vrInpatientVisitRecord);

                    }
                    break;
                case SURGICAL_RECORD:
                    VrSurgicalRecord vrSurgicalRecord =
                            vrSurgicalRecordDAO.get(businessId);
                    if (vrSurgicalRecord != null) {
                        savePatientSatisfactionSurvey(survey, vrSurgicalRecord);
                    }
                    break;
                case INSPECTION_RECORD:
                case CHECK_RECORD:
                case TREATMENT_RECORD:
                    VrApplicationFormRecord vrApplicationFormRecord =
                            vrApplicationFormRecordDAO.get(businessId);
                    if (vrApplicationFormRecord != null) {
                        savePatientSatisfactionSurvey(survey, vrApplicationFormRecord);
                    }
                    break;
                case DISPENSING_RECORD:
                    VrDispensingRecord vrDispensingRecord =
                            vrDispensingRecordDAO.get(businessId);
                    if (vrDispensingRecord != null) {
                        savePatientSatisfactionSurvey(survey, vrDispensingRecord);
                    }
                    break;
                default:
                    break;
            }
            //更新调查次数
            updateSurveyNumber(businessType, businessId);
        }

        //保存表单
        List<FollowUpQuestionnaireDTO> questionnaireList = request.getQuestionnaireList();
        if (!CollectionUtils.isEmpty(questionnaireList)) {
            questionnaireList.stream().map(q -> {
                SatisfactionRequisitionRecord record = new SatisfactionRequisitionRecord();
                record.setFormId(KeyGenerator.randomGenerate());
                record.setRecordId(survey.getPatientSurveyId());
                record.setCreateId(operatorId);
                record.setCreateDt(new Date());
                record.setModifyDt(new Date());
                record.setQuestionnaireId(q.getQuestionnaireId());
                record.setQuestionnaireName(q.getQuestionnaireName());
                return record;
            }).forEach(q -> satisfactionRequisitionRecordDAO.insertSelective(q));
        }

        //保存宣教
        List<FollowUpEducationDTO> educationList = request.getEducationList();
        if (!CollectionUtils.isEmpty(educationList)) {
            educationList.stream().map(q -> {
                SatisfactionHealthEducation e = new SatisfactionHealthEducation();
                e.setId(KeyGenerator.randomGenerate());
                e.setRecordId(survey.getPatientSurveyId());
                e.setEducationId(q.getEducationId());
                e.setEducationName(q.getEducationName());
                e.setDefaultPush(0);
                e.setCreateDt(new Date());
                e.setModifyDt(new Date());
                return e;
            }).forEach(e -> satisfactionHealthEducationDAO.insertSelective(e));
        }
        return survey;
    }

    /**
     * @param now
     * @param businessId
     * @param businessType
     * @param isNotify
     * @param operatorId
     * @param questionnaireList 表单列表
     * @param surveyRuleId
     * @param surveyRuleName
     * @throws
     * @description: 保存满意度调查计划
     * @return: void
     * @author: tongtp
     * @date: 2020/9/12 16:03
     */
//    private void saveSatisfactionSurvey(Date now, String businessId, String businessType, String isNotify,
//                                        String operatorId, List<FollowUpQuestionnaireDTO> questionnaireList,
//                                        List<FollowUpEducationDTO> educationList,
//                                        Long surveyRuleId, String surveyRuleName, boolean saveProduceRecord,
//                                        Long rulePlanId,
//                                        String planFrequency, String planFrequencyTime, Integer planFrequencyNumber
//            , String startTimeType, Integer timeNodeSize, String timeNodeSizeUnit) {
//        PatientSatisfactionSurvey patientSatisfactionSurvey = new PatientSatisfactionSurvey();
//        if (isNotify == null) {
//            //是否通知患者，0不通知，1通知
//            isNotify = "0";
//        }
//        patientSatisfactionSurvey.setIsNotify(isNotify);
//        patientSatisfactionSurvey.setProcessingStatus("0");
//        patientSatisfactionSurvey.setCreatorId(operatorId);
//        patientSatisfactionSurvey.setGmtCreate(now);
//        patientSatisfactionSurvey.setModifyId(operatorId);
//        patientSatisfactionSurvey.setGmtModified(now);
////        patientSatisfactionSurvey.setQuestionnaireId(questionnaireId);
////        patientSatisfactionSurvey.setQuestionnaireName(questionnaireName);
//        patientSatisfactionSurvey.setSurveyStatus("0");
//        patientSatisfactionSurvey.setNotifyStatus("0");
//        patientSatisfactionSurvey.setSurveyRuleId(surveyRuleId);
//        patientSatisfactionSurvey.setSurveyRuleName(surveyRuleName);
//        //居民对处理结果的确认状态 1：已确认   0：未确认
//        patientSatisfactionSurvey.setConfirmStatus("0");
//        patientSatisfactionSurvey.setBusinessId(businessId);
//        patientSatisfactionSurvey.setBusinessType(businessType);
//
//        Calendar planTimeInstance = Calendar.getInstance();
//
//        VisitRecordEnum enumByKey = getEnumByKey(businessType);
//        if (enumByKey != null) {
//            switch (enumByKey) {
//                case OUTPATIENT_VISIT_RECORD:
//                    VrOutpatientVisitRecord vrOutpatientVisitRecord =
//                            vrOutpatientVisitRecordDAO.get(businessId);
//                    if (vrOutpatientVisitRecord != null) {
//                        if (saveProduceRecord) {
//                            Integer intervalTime = getIntervalTime(planFrequencyTime);
//                            Date startPlanTime = getStartPlanTime(vrOutpatientVisitRecord, startTimeType,
//                                    timeNodeSize, timeNodeSizeUnit);
//                            if ("1".equals(planFrequency) || planFrequencyNumber == null) {
//                                planFrequencyNumber = 1;
//                            }
//                            for (int i = 0; i < planFrequencyNumber; i++) {
//                                planTimeInstance.setTime(startPlanTime);
//                                planTimeInstance.add(Calendar.DAY_OF_YEAR, intervalTime * i);
//                                patientSatisfactionSurvey.setPlanSurveyTime(planTimeInstance.getTime());
//                                String patientSurveyId = Utils.getUUID();
//                                patientSatisfactionSurvey.setPatientSurveyId(patientSurveyId);
//                                savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrOutpatientVisitRecord);
//                                if (saveProduceRecord) {
//                                    saveProduceRecord = false;
//                                    saveSatisfactionProduceRecord(now, businessId, businessType, operatorId,
//                                            surveyRuleId,
//                                            rulePlanId, patientSurveyId);
//                                }
//                            }
//                        } else {
//                            patientSatisfactionSurvey.setPlanSurveyTime(now);
//                            patientSatisfactionSurvey.setPatientSurveyId(Utils.getUUID());
//                            savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrOutpatientVisitRecord);
//                        }
//                    }
//                    break;
//                case INPATIENT_VISIT_RECORD:
//                    VrInpatientVisitRecord vrInpatientVisitRecord =
//                            vrInpatientVisitRecordDAO.get(businessId);
//                    if (vrInpatientVisitRecord != null) {
//                        if (saveProduceRecord) {
//                            Integer intervalTime = getIntervalTime(planFrequencyTime);
//                            Date startPlanTime = getStartPlanTime(vrInpatientVisitRecord, startTimeType,
//                                    timeNodeSize, timeNodeSizeUnit);
//                            if ("1".equals(planFrequency) || planFrequencyNumber == null) {
//                                planFrequencyNumber = 1;
//                            }
//                            for (int i = 0; i < planFrequencyNumber; i++) {
//                                planTimeInstance.setTime(startPlanTime);
//                                planTimeInstance.add(Calendar.DAY_OF_YEAR, intervalTime * i);
//                                patientSatisfactionSurvey.setPlanSurveyTime(planTimeInstance.getTime());
//                                String patientSurveyId = Utils.getUUID();
//                                patientSatisfactionSurvey.setPatientSurveyId(patientSurveyId);
//                                savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrInpatientVisitRecord);
//                                if (saveProduceRecord) {
//                                    saveProduceRecord = false;
//                                    saveSatisfactionProduceRecord(now, businessId, businessType, operatorId,
//                                            surveyRuleId,
//                                            rulePlanId, patientSurveyId);
//                                }
//                            }
//                        } else {
//                            patientSatisfactionSurvey.setPatientSurveyId(Utils.getUUID());
//                            patientSatisfactionSurvey.setPlanSurveyTime(now);
//                            savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrInpatientVisitRecord);
//                        }
//                    }
//                    break;
//                case SURGICAL_RECORD:
//                    VrSurgicalRecord vrSurgicalRecord =
//                            vrSurgicalRecordDAO.get(businessId);
//                    if (vrSurgicalRecord != null) {
//                        if (saveProduceRecord) {
//                            Integer intervalTime = getIntervalTime(planFrequencyTime);
//                            Date startPlanTime = getStartPlanTime(vrSurgicalRecord, startTimeType,
//                                    timeNodeSize, timeNodeSizeUnit);
//                            if ("1".equals(planFrequency) || planFrequencyNumber == null) {
//                                planFrequencyNumber = 1;
//                            }
//                            for (int i = 0; i < planFrequencyNumber; i++) {
//                                planTimeInstance.setTime(startPlanTime);
//                                planTimeInstance.add(Calendar.DAY_OF_YEAR, intervalTime * i);
//                                patientSatisfactionSurvey.setPlanSurveyTime(planTimeInstance.getTime());
//                                String patientSurveyId = Utils.getUUID();
//                                patientSatisfactionSurvey.setPatientSurveyId(patientSurveyId);
//                                savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrSurgicalRecord);
//                                if (saveProduceRecord) {
//                                    saveProduceRecord = false;
//                                    saveSatisfactionProduceRecord(now, businessId, businessType, operatorId,
//                                            surveyRuleId,
//                                            rulePlanId, patientSurveyId);
//                                }
//                            }
//                        } else {
//                            patientSatisfactionSurvey.setPlanSurveyTime(now);
//                            patientSatisfactionSurvey.setPatientSurveyId(Utils.getUUID());
//                            savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrSurgicalRecord);
//                        }
//                    }
//                    break;
//                case INSPECTION_RECORD:
//                case CHECK_RECORD:
//                case TREATMENT_RECORD:
//                    VrApplicationFormRecord vrApplicationFormRecord =
//                            vrApplicationFormRecordDAO.get(businessId);
//                    if (vrApplicationFormRecord != null) {
//                        if (saveProduceRecord) {
//                            Integer intervalTime = getIntervalTime(planFrequencyTime);
//                            Date startPlanTime = getStartPlanTime(vrApplicationFormRecord, startTimeType,
//                                    timeNodeSize, timeNodeSizeUnit);
//                            if ("1".equals(planFrequency) || planFrequencyNumber == null) {
//                                planFrequencyNumber = 1;
//                            }
//                            for (int i = 0; i < planFrequencyNumber; i++) {
//                                planTimeInstance.setTime(startPlanTime);
//                                planTimeInstance.add(Calendar.DAY_OF_YEAR, intervalTime * i);
//                                patientSatisfactionSurvey.setPlanSurveyTime(planTimeInstance.getTime());
//                                String patientSurveyId = Utils.getUUID();
//                                patientSatisfactionSurvey.setPatientSurveyId(patientSurveyId);
//                                savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrApplicationFormRecord);
//                                if (saveProduceRecord) {
//                                    saveProduceRecord = false;
//                                    saveSatisfactionProduceRecord(now, businessId, businessType, operatorId,
//                                            surveyRuleId,
//                                            rulePlanId, patientSurveyId);
//                                }
//                            }
//                        } else {
//                            patientSatisfactionSurvey.setPlanSurveyTime(now);
//                            patientSatisfactionSurvey.setPatientSurveyId(Utils.getUUID());
//                            savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrApplicationFormRecord);
//                        }
//                    }
//                    break;
//                case DISPENSING_RECORD:
//                    VrDispensingRecord vrDispensingRecord =
//                            vrDispensingRecordDAO.get(businessId);
//                    if (vrDispensingRecord != null) {
//                        if (saveProduceRecord) {
//                            Integer intervalTime = getIntervalTime(planFrequencyTime);
//                            Date startPlanTime = getStartPlanTime(vrDispensingRecord, startTimeType,
//                                    timeNodeSize, timeNodeSizeUnit);
//                            if ("1".equals(planFrequency) || planFrequencyNumber == null) {
//                                planFrequencyNumber = 1;
//                            }
//                            for (int i = 0; i < planFrequencyNumber; i++) {
//                                planTimeInstance.setTime(startPlanTime);
//                                planTimeInstance.add(Calendar.DAY_OF_YEAR, intervalTime * i);
//                                patientSatisfactionSurvey.setPlanSurveyTime(planTimeInstance.getTime());
//                                String patientSurveyId = Utils.getUUID();
//                                patientSatisfactionSurvey.setPatientSurveyId(patientSurveyId);
//                                savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrDispensingRecord);
//                                if (saveProduceRecord) {
//                                    saveProduceRecord = false;
//                                    saveSatisfactionProduceRecord(now, businessId, businessType, operatorId,
//                                            surveyRuleId,
//                                            rulePlanId, patientSurveyId);
//                                }
//                            }
//                        } else {
//                            patientSatisfactionSurvey.setPlanSurveyTime(now);
//                            patientSatisfactionSurvey.setPatientSurveyId(Utils.getUUID());
//                            savePatientSatisfactionSurvey(patientSatisfactionSurvey, vrDispensingRecord);
//                        }
//                    }
//                    break;
//                default:
//                    break;
//            }
//            //更新调查次数
//            updateSurveyNumber(businessType, businessId);
//        }
//
//        //保存表单
//        questionnaireList.stream().map(q->{
//            SatisfactionRequisitionRecord record = new SatisfactionRequisitionRecord();
//            record.setFormId(KeyGenerator.randomGenerate());
//            record.setRecordId(patientSatisfactionSurvey.getPatientSurveyId());
//            record.setCreateId(operatorId);
//            record.setCreateDt(new Date());
//            record.setModifyDt(new Date());
//            record.setQuestionnaireId(q.getQuestionnaireId());
//            record.setQuestionnaireName(q.getQuestionnaireName());
//            return record;
//        }).forEach(q->satisfactionRequisitionRecordDAO.insertSelective(q));
//
//        //保存宣教
//        educationList.stream().map(q->{
//            SatisfactionHealthEducation e = new SatisfactionHealthEducation();
//            e.setId(KeyGenerator.randomGenerate());
//            e.setRecordId(patientSatisfactionSurvey.getPatientSurveyId());
//            e.setEducationId(q.getEducationId());
//            e.setEducationName(q.getEducationName());
//            e.setDefaultPush(0);
//            e.setCreateDt(new Date());
//            e.setModifyDt(new Date());
//            return e;
//        }).forEach(e->satisfactionHealthEducationDAO.insertSelective(e));
//    }

    /**
     * @param planFrequencyTime
     * @throws
     * @description: 计算得到间隔时间-天数
     * @return: java.lang.Integer
     * @author: tongtp
     * @date: 2020/7/28 17:40
     */
    private Integer getIntervalTime(String planFrequencyTime) {
        //计划频次时间，长期时需要填写，1每天一次,2每周一次,3每4周一次,4每月一次,5每3月一次,6每半年一次,7每年一次
        Integer intervalTime = 0;
        if (planFrequencyTime != null) {
            switch (planFrequencyTime) {
                case "1":
                    intervalTime = 1;
                    break;
                case "2":
                    intervalTime = 7;
                    break;
                case "3":
                    intervalTime = 28;
                    break;
                case "4":
                    intervalTime = 30;
                    break;
                case "5":
                    intervalTime = 90;
                    break;
                case "6":
                    intervalTime = 180;
                    break;
                case "7":
                    intervalTime = 365;
                    break;
                default:
                    break;
            }
        }
        return intervalTime;
    }

    /**
     * @param vrOutpatientVisitRecord
     * @param startTimeType
     * @param timeNodeSize
     * @param timeNodeSizeUnit
     * @throws
     * @description: 计算得到满意度调查计划时间起点
     * @return: java.util.Date
     * @author: tongtp
     * @date: 2020/9/12 21:26
     */
    private Date getStartPlanTime(VrOutpatientVisitRecord vrOutpatientVisitRecord, String startTimeType,
                                  Integer timeNodeSize, String timeNodeSizeUnit) {
        //开始时间类型 1:就诊时间  2:入院时间  3:出院时间  4:手术时间  5:申请时间  6:执行时间  7:报告时间  8:处方时间  9:取药时间
        //门诊：就诊时间
        Date startPlanTime = null;
        if ("1".equals(startTimeType)) {
            startPlanTime = vrOutpatientVisitRecord.getStartTime();
        }
        if (startPlanTime == null) {
            //为空默认为当前时间
            startPlanTime = new Date();
        }
        startPlanTime = handleStartPlanTime(timeNodeSize, timeNodeSizeUnit, startPlanTime);
        return startPlanTime;
    }


    /**
     * @param vrSurgicalRecord
     * @param startTimeType
     * @param timeNodeSize
     * @param timeNodeSizeUnit
     * @throws
     * @description: 计算得到满意度调查计划时间起点
     * @return: java.util.Date
     * @author: tongtp
     * @date: 2020/9/12 21:26
     */
    private Date getStartPlanTime(VrSurgicalRecord vrSurgicalRecord, String startTimeType,
                                  Integer timeNodeSize,
                                  String timeNodeSizeUnit) {
        //开始时间类型 1:就诊时间  2:入院时间  3:出院时间  4:手术时间  5:申请时间  6:执行时间  7:报告时间  8:处方时间  9:取药时间
        //手术：手术时间
        Date startPlanTime = null;
        if ("1".equals(startTimeType)) {
            startPlanTime = vrSurgicalRecord.getStartTime();
        }
        if (startPlanTime == null) {
            //为空默认为当前时间
            startPlanTime = new Date();
        }
        startPlanTime = handleStartPlanTime(timeNodeSize, timeNodeSizeUnit, startPlanTime);
        return startPlanTime;
    }

    /**
     * @param vrApplicationFormRecord
     * @param startTimeType
     * @param timeNodeSize
     * @param timeNodeSizeUnit
     * @throws
     * @description: 计算得到满意度调查计划时间起点
     * @return: java.util.Date
     * @author: tongtp
     * @date: 2020/9/12 21:26
     */
    private Date getStartPlanTime(VrApplicationFormRecord vrApplicationFormRecord, String startTimeType,
                                  Integer timeNodeSize, String timeNodeSizeUnit) {
        //开始时间类型 1:就诊时间  2:入院时间  3:出院时间  4:手术时间  5:申请时间  6:执行时间  7:报告时间  8:处方时间  9:取药时间
        Date startPlanTime = null;
        if ("1".equals(vrApplicationFormRecord.getBillCategoryCode())
                && "2".equals(vrApplicationFormRecord.getBillCategoryCode())) {
            //billCategoryCode  1:检验  2:检查  3:处置
            //检验/检查：申请时间 执行时间 报告时间
            if ("5".equals(startTimeType)) {
                startPlanTime = vrApplicationFormRecord.getOpenTime();
            }
            if ("6".equals(startTimeType)) {
                startPlanTime = vrApplicationFormRecord.getExecutiveTime();
            }
            if ("7".equals(startTimeType)) {
                startPlanTime = vrApplicationFormRecord.getReportTime();
            }
        }
        if ("3".equals(vrApplicationFormRecord.getBillCategoryCode())) {
            //billCategoryCode  1:检验  2:检查  3:处置
            //治疗: 申请日期  执行日期
            if ("5".equals(startTimeType)) {
                startPlanTime = vrApplicationFormRecord.getOpenTime();
            }
            if ("6".equals(startTimeType)) {
                startPlanTime = vrApplicationFormRecord.getExecutiveTime();
            }
        }
        if (startPlanTime == null) {
            //为空默认为当前时间
            startPlanTime = new Date();
        }
        startPlanTime = handleStartPlanTime(timeNodeSize, timeNodeSizeUnit, startPlanTime);
        return startPlanTime;
    }

    /**
     * @param vrDispensingRecord
     * @param startTimeType
     * @param timeNodeSize
     * @param timeNodeSizeUnit
     * @throws
     * @description: 计算得到满意度调查计划时间起点
     * @return: java.util.Date
     * @author: tongtp
     * @date: 2020/9/12 21:26
     */
    private Date getStartPlanTime(VrDispensingRecord vrDispensingRecord, String startTimeType,
                                  Integer timeNodeSize,
                                  String timeNodeSizeUnit) {
        //开始时间类型 1:就诊时间  2:入院时间  3:出院时间  4:手术时间  5:申请时间  6:执行时间  7:报告时间  8:处方时间  9:取药时间
        //取药：处方时间 取药时间
        Date startPlanTime = null;
        if ("1".equals(startTimeType)) {
            if ("8".equals(startTimeType)) {
                startPlanTime = vrDispensingRecord.getPrescriptionTime();
            }
            if ("9".equals(startTimeType)) {
                startPlanTime = vrDispensingRecord.getDispensingDate();
            }
        }
        if (startPlanTime == null) {
            //为空默认为当前时间
            startPlanTime = new Date();
        }
        startPlanTime = handleStartPlanTime(timeNodeSize, timeNodeSizeUnit, startPlanTime);
        return startPlanTime;
    }

    /**
     * @param vrInpatientVisitRecord
     * @param startTimeType
     * @param timeNodeSize
     * @param timeNodeSizeUnit
     * @throws
     * @description: 计算得到满意度调查计划时间起点
     * @return: java.util.Date
     * @author: tongtp
     * @date: 2020/9/12 21:26
     */
    private Date getStartPlanTime(VrInpatientVisitRecord vrInpatientVisitRecord, String startTimeType,
                                  Integer timeNodeSize, String timeNodeSizeUnit) {
        //开始时间类型 1:就诊时间  2:入院时间  3:出院时间  4:手术时间  5:申请时间  6:执行时间  7:报告时间  8:处方时间  9:取药时间
        //住院：入院时间 出院时间
        Date startPlanTime = null;
        if ("1".equals(startTimeType)) {
            if ("2".equals(startTimeType)) {
                startPlanTime = vrInpatientVisitRecord.getAdmissionTime();
            }
            if ("3".equals(startTimeType)) {
                startPlanTime = vrInpatientVisitRecord.getDischargeTime();
            }
        }
        if (startPlanTime == null) {
            //为空默认为当前时间
            startPlanTime = new Date();
        }
        startPlanTime = handleStartPlanTime(timeNodeSize, timeNodeSizeUnit, startPlanTime);
        return startPlanTime;
    }

    /**
     * @param timeNodeSize
     * @param timeNodeSizeUnit
     * @param startPlanTime
     * @throws
     * @description: 处理计划开始时间
     * @return: java.util.Date
     * @author: tongtp
     * @date: 2020/9/13 12:02
     */
    private Date handleStartPlanTime(Integer timeNodeSize, String timeNodeSizeUnit, Date startPlanTime) {
        if (startPlanTime != null && timeNodeSize != null && timeNodeSizeUnit != null) {
            //时间间隔-天数
            Integer timeInterval = 0;
            switch (timeNodeSizeUnit) {
                case "1":
                    timeInterval = timeNodeSize;
                    break;
                case "2":
                    timeInterval = timeNodeSize * 7;
                    break;
                case "3":
                    timeInterval = timeNodeSize * 30;
                    break;
                default:
                    break;
            }
            Calendar instance = Calendar.getInstance();
            instance.setTime(startPlanTime);
            instance.add(Calendar.DAY_OF_YEAR, timeInterval);
            startPlanTime = instance.getTime();
        }
        return startPlanTime;
    }

    /**
     * @param now
     * @param businessId
     * @param businessType
     * @param operatorId
     * @param surveyRuleId
     * @param rulePlanId
     * @param patientSurveyId
     * @throws
     * @description: 保存满意度生成记录
     * @return: void
     * @author: tongtp
     * @date: 2020/9/12 19:29
     */
    private void saveSatisfactionProduceRecord(Date now, String businessId, String businessType,
                                               String operatorId,
                                               Long surveyRuleId, Long rulePlanId, String patientSurveyId) {
        SatisfactionProduceRecord satisfactionProduceRecord = new SatisfactionProduceRecord();
        satisfactionProduceRecord.setPatientSurveyId(patientSurveyId);
        satisfactionProduceRecord.setBusinessType(businessType);
        satisfactionProduceRecord.setBusinessId(businessId);
        satisfactionProduceRecord.setRouteId(surveyRuleId);
        satisfactionProduceRecord.setRouteDetailId(rulePlanId);
        satisfactionProduceRecord.setCreatorId(operatorId);
        satisfactionProduceRecord.setGmtCreate(now);
        satisfactionProduceRecordDAO.save(satisfactionProduceRecord);
    }
}
